﻿using System;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.IO; 
namespace Basic.Base.System.FileHelper;

public class FileHelper : IDisposable
{

    private bool _alreadyDispose = false;

    #region 构造函数
    public FileHelper()
    {

    }
    ~FileHelper()
    {
        Dispose();
    }

    protected virtual void Dispose(bool isDisposing)
    {
        if (_alreadyDispose) return;
        _alreadyDispose = true;
    }
    #endregion


    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }



    #region 取得文件后缀名

    /// <summary>
    /// 取后缀名
    /// </summary>
    /// <param name="filename">文件名</param>
    /// <returns>.gif|.html格式</returns>
    public static string GetPostfixStr(string filename)
    {
        int start = filename.LastIndexOf(".");
        int length = filename.Length;
        string postfix = filename.Substring(start, length - start);
        return postfix;
    }
    #endregion

    #region 根据文件大小获取指定前缀的可用文件名
    /// <summary>
    /// 根据文件大小获取指定前缀的可用文件名
    /// </summary>
    /// <param name="folderPath">文件夹</param>
    /// <param name="prefix">文件前缀</param>
    /// <param name="size">文件大小(1m)</param>
    /// <param name="ext">文件后缀(.log)</param>
    /// <returns>可用文件名</returns>
    public static string GetAvailableFileWithPrefixOrderSize(string folderPath, string prefix, int size = 1 * 1024 * 1024, string ext = ".log")
    {
        var allFiles = new DirectoryInfo(folderPath);
        var selectFiles = allFiles.GetFiles().Where(fi => fi.Name.ToLower().Contains(prefix.ToLower()) && fi.Extension.ToLower() == ext.ToLower() && fi.Length < size).OrderByDescending(d => d.Name).ToList();

        if (selectFiles.Count > 0)
        {
            return selectFiles.FirstOrDefault().FullName;
        }

        return Path.Combine(folderPath, $@"{prefix}_{DateTime.Now.ToEpochTimeSpan()}.log");
    }
    public static string GetAvailableFileNameWithPrefixOrderSize(string _contentRoot, string prefix, int size = 1 * 1024 * 1024, string ext = ".log")
    {
        var folderPath = Path.Combine(_contentRoot, "Log");
        if (!Directory.Exists(folderPath))
        {
            Directory.CreateDirectory(folderPath);
        }

        var allFiles = new DirectoryInfo(folderPath);
        var selectFiles = allFiles.GetFiles().Where(fi => fi.Name.ToLower().Contains(prefix.ToLower()) && fi.Extension.ToLower() == ext.ToLower() && fi.Length < size).OrderByDescending(d => d.Name).ToList();

        if (selectFiles.Count > 0)
        {
            return selectFiles.FirstOrDefault().Name.Replace(".log", "");
        }

        return $@"{prefix}_{DateTime.Now.ToEpochTimeSpan()}";
    }
    #endregion




    /// <summary>
    /// 写文件
    /// </summary>
    /// <param name="Path">文件路径</param>
    /// <param name="Strings">文件内容</param>
    public static void WriteFile(string Path, byte[] buf)
    {
        if (!File.Exists(Path))
        {
            FileStream f = File.Create(Path);
            f.Close();
        }
        FileStream f2 = new FileStream(Path, FileMode.Create, FileAccess.Write);
        f2.Write(buf, 0, buf.Length);
        f2.Close();
        f2.Dispose();
    }

    /// <summary>
    /// 写文件
    /// </summary>
    /// <param name="Path">文件路径</param>
    /// <param name="Strings">文件内容</param>
    /// <param name="encode">编码格式</param>
    public static void WriteFile(string Path, string Strings, Encoding encode)
    {
        if (!File.Exists(Path))
        {
            FileStream f = File.Create(Path);
            f.Close();
        }
        StreamWriter f2 = new StreamWriter(Path, false, encode);
        f2.Write(Strings);
        f2.Close();
        f2.Dispose();
    }




    /// <summary>
    /// 读文件
    /// </summary>
    /// <param name="Path">文件路径</param>
    /// <param name="encode">编码格式</param>
    /// <returns></returns>
    public static string ReadFile(string Path, Encoding encode)
    {
        string s = "";
        if (!File.Exists(Path))
            s = "不存在相应的目录";
        else
        {
            StreamReader f2 = new StreamReader(Path, encode);
            s = f2.ReadToEnd();
            f2.Close();
            f2.Dispose();
        }

        return s;
    }


    #region 拷贝文件

    /// <summary>
    /// 拷贝文件
    /// </summary>
    /// <param name="OrignFile">原始文件</param>
    /// <param name="NewFile">新文件路径</param>
    public static void FileCoppy(string orignFile, string NewFile)
    {
        File.Copy(orignFile, NewFile, true);
    }

    #endregion

    #region 删除文件

    /// <summary>
    /// 删除文件
    /// </summary>
    /// <param name="Path">路径</param>
    public static void FileDel(string Path)
    {
        File.Delete(Path);
    }
    #endregion

    #region 移动文件

    /// <summary>
    /// 移动文件
    /// </summary>
    /// <param name="OrignFile">原始路径</param>
    /// <param name="NewFile">新路径</param>
    public static void FileMove(string orignFile, string NewFile)
    {
        File.Move(orignFile, NewFile);
    }
    #endregion

    #region 在当前目录下创建目录

    /// <summary>
    /// 在当前目录下创建目录
    /// </summary>
    /// <param name="OrignFolder">当前目录</param>
    /// <param name="NewFloder">新目录</param>
    public static void FolderCreate(string orignFolder, string NewFloder)
    {
        Directory.SetCurrentDirectory(orignFolder);
        Directory.CreateDirectory(NewFloder);
    }
    #endregion

    #region 压缩文件
     

    public static string ZipFiles(Dictionary<string, byte[]> fileData, string zipFile, string zipName)
    {
        string fileName = $"{zipFile}\\{zipName}";
        if (!Directory.Exists(fileName))
        {
            Directory.CreateDirectory(fileName);
        }
        Stream stream;
        foreach (var item in fileData)
        {
            stream=  new MemoryStream(item.Value); 
            using (FileStream zipCreate = new FileStream($"{fileName}\\{item.Key}", FileMode.Create))
            {
                stream.CopyTo(zipCreate);
            }
        } 
        ZipFile.CreateFromDirectory(fileName, fileName + ".zip");
        return $"{fileName}.zip";

    }
    #endregion
}
